package com.sllp.C71S3TsllpShop.web;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttribute;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.sllp.C71S3TsllpShop.bean.Address;
import com.sllp.C71S3TsllpShop.bean.AlipayConfig;
import com.sllp.C71S3TsllpShop.bean.BigType;
import com.sllp.C71S3TsllpShop.bean.Car;
import com.sllp.C71S3TsllpShop.bean.OrdersItem;
import com.sllp.C71S3TsllpShop.bean.OrdersItemExample;
import com.sllp.C71S3TsllpShop.bean.Result;
import com.sllp.C71S3TsllpShop.bean.User;
import com.sllp.C71S3TsllpShop.biz.impl.CarBizImpl;
import com.sllp.C71S3TsllpShop.biz.impl.OrdersItemBizImpl;
import com.sllp.C71S3TsllpShop.dao.CarMapper;
import com.sllp.C71S3TsllpShop.dao.OrdersItemMapper;
import com.sllp.C71S3TsllpShop.dao.OrdersMapper;
import com.sllp.C71S3TsllpShop.dao.ProductMapper;
import com.sllp.C71S3TsllpShop.dao.UserMapper;


@Controller
public class CarAction {

	@Resource
	private UserMapper um;
	
	@Resource
	private CarBizImpl cbi ; 
	
	@Resource
	private CarMapper cm;
	
	@Resource
	private ProductMapper pm;

	@Resource
	private OrdersMapper om;
	
	@Resource
	private OrdersItemMapper oim;
	
	//购物车界面一显示
	@GetMapping("BuyCar.do")
	public String Cart(HttpSession session,@SessionAttribute("btlist") List<List<BigType>> lists,
			@SessionAttribute(name="loginUser",required=false) User user,Model m) {
		m.addAttribute("btlist", lists);
		// 购物车
		List<Car>list=cbi.Cart2(user.getId());
		if(list.size()==0) {
			return "Index";
		}
		System.out.println(list);
		//算出总价
		BigDecimal totel =new BigDecimal(0);
		BigDecimal number = new BigDecimal(0);//用于将商品数量转为Bigdecimal属性
		
		for(Car car :list) {
			int value=car.getCount();
			number=BigDecimal.valueOf((int)value);
			totel=totel.add(car.getProductSpecs().getProductPrice().multiply(number));
		}
		m.addAttribute("totel", totel);
		m.addAttribute("carlist", list);
		return "BuyCar";
	}
	
	//购物车界面二显示
	@GetMapping("BuyCartwo.do")
	public String Carttwo(@SessionAttribute(name="loginUser",required=false) User user,Model m) {
		List<Object> obj =new ArrayList<Object>();
		obj=cbi.Carttwo2(user.getId());
		User u = (User)obj.get(1);
		List<Car> list = (List<Car>)obj.get(0);
		List<Address>alist=(List<Address>)obj.get(2);
		//算出总价
		BigDecimal totel =new BigDecimal(0);
		BigDecimal number = new BigDecimal(0);//用于将商品数量转为Bigdecimal属性
		
		for(Car car :list) {
			int value=car.getCount();
			number=BigDecimal.valueOf((int)value);
			totel=totel.add(car.getProductSpecs().getProductPrice().multiply(number));
		}
		
		m.addAttribute("totel", totel);
		m.addAttribute("carlist",list);
		m.addAttribute("user", u);
		m.addAttribute("alist", alist);
		return "BuyCar_Two";
	}

	
	
	//购物车界面三
	@GetMapping("BuyCarThree.do")
	/**
	 * @param m
	 * @param tp
	 * @param text
	 * @return
	 */
	public String CarThree( Model m,HttpSession session){
		//List<Object> list = new ArrayList<Object>();
		//list=cbi.Carthree3( s);
		//cbi.Carthree3(s);
		
		BigDecimal tp=(BigDecimal) session.getAttribute("Totel");
		String id =(String)session.getAttribute("Ordersid");
		System.out.println("orderidtp:"+tp);
		System.out.println("orderid:"+id);
		
		
		m.addAttribute("totel", tp);
		m.addAttribute("ordersid",id);
		
		// 是否已支付
		m.addAttribute("paySucess", 0);
		return "BuyCar_Three";
	}
	
	
	//购物结算
	@ResponseBody
	@PostMapping("settle.do")
	/**
	 * @param m
	 * @param tp
	 * @param text
	 * @return
	 */
	public Result Settle( BigDecimal tp ,String text,HttpSession session ) {
		User user = (User) session.getAttribute("loginUser");
		int ok = cbi.Settle2(user,tp, text,session);
		if(ok>0) {
			return new Result(ok,"结算成功");
		}
		return new Result(ok, "结算失败"); 
	}
	

	
	//删除购物车信息
	@ResponseBody
	@PostMapping("deletecar.do")
	public Result deleteCar(int specs) {
		int ok = cbi.deleteCar2(specs);
		if(ok>0) {
			return new Result(ok,"删除成功");
		}
		return new Result(ok, "删除失败"); 
	}
		
	
	
	//修改购物车信息
	@ResponseBody
	@PostMapping("modifycar.do")
	public Result modifyCar(int count ,int carid) {
		System.out.println(carid);
		int ok = cbi.modifyCar2(count,carid);
		if(ok>0) {
			return new Result(ok,"修改成功");
		}
		return new Result(ok, "修改失败"); 
	}
	
	//修改用户信息
	@ResponseBody
	@PostMapping("modifyUser.do")
	public Result modifyUser(@SessionAttribute(name="loginUser",required=false) User user,
			String useraddr,String userpostal,String usertel) {
		int ok = cbi.modifyUser2(user.getId() ,useraddr,userpostal,usertel);
		System.out.println(ok);
		if(ok>0) {
			return new Result(ok,"修改成功");
		}
		return new Result(ok, "修改失败"); 
	}
	
	@GetMapping("paySuccess.do")
	public String paySuccess(String out_trade_no,BigDecimal total_amount,HttpServletRequest request,HttpServletResponse response,Model m) {
		
		
		try {
			m.addAttribute("totel", total_amount);
			m.addAttribute("ordersid",out_trade_no);
			
			//获取支付宝GET过来反馈信息
			Map<String,String> params = new HashMap<String,String>();
			Map<String,String[]> requestParams = request.getParameterMap();
			for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
				String name = (String) iter.next();
				String[] values = (String[]) requestParams.get(name);
				String valueStr = "";
				for (int i = 0; i < values.length; i++) {
					valueStr = (i == values.length - 1) ? valueStr + values[i]
							: valueStr + values[i] + ",";
				}
				//乱码解决，这段代码在出现乱码时使用
				valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
				params.put(name, valueStr);
			}
			
			boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名

			//——请在这里编写您的程序（以下代码仅作参考）——
			if(signVerified) {
				m.addAttribute("paySucess", 1);
				
				OrdersItemExample ordersItemExample = new OrdersItemExample();
				ordersItemExample.createCriteria().andIdEqualTo(out_trade_no);
				OrdersItem ordersItem = new OrdersItem();
				ordersItem.setState(2);
				int code = oim.updateByExampleSelective(ordersItem, ordersItemExample);
				System.out.println(code);
			}else {
				m.addAttribute("paySucess", 0);
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (AlipayApiException e) {
			e.printStackTrace();
		}
		return "BuyCar_Three";
	}
	
	@ModelAttribute
	public void searchCar(@SessionAttribute("loginUser") User user,Model m) {
		if(user != null) {
			List<Car> clist=cbi.findCar(user);
			m.addAttribute("clist", clist);
		}
	}

}
